<?php
namespace app\common\logic;

use app\common\exception\FailException;
use fast\Random;
use think\Controller;
use think\Db;
use think\Exception;

class Recharge extends Controller
{
    public static function get_recharge($uid){
        $user_data=Db::table("t_user")->where("id",$uid)->where("status",1)->find(); //等级id
        $roleid=$user_data['role_id'];
        if(!$roleid){

            throw new FailException(['code' => 201,"msg"=>"该用户还未选择角色","errorCode"=>404]);
        }
        //获取会员等级信息

        $user_role=Db::table("t_user_role")->where("id",$roleid)->find();
        $cdata = Db::table("t_capital")->where("uid",$uid)->where("status",1)->lock(true)->find();

        $data=[
                 "max_recharge"=>$user_role['new_recharge'],
                 "lj_recharge"=>$cdata['recharge'],
                 "rmax_recharge"=>$user_role['new_recharge']-$cdata['recharge'],
                 "username"=>$user_data['username']
        ];
        return $data;


    }

    public static function recharge_list($uid,$start=1,$num=20,$type=[],$start_time='',$end_time=''){

        $where=[];
        if($start_time){
            $start_time=strtotime($start_time);
            $where['addtime']=['egt',$start_time];
        }

        if($end_time){
            $end_time=strtotime($end_time);
            $where['addtime']=['elt',$end_time];
        }

        if($start_time&&$end_time){
            $where['addtime']=['between',[$start_time,$end_time]];
        }


        if($type){
            $where['recharge_type']=['in',$type];
        }
        $data=\app\common\model\Recharge::where("uid",$uid)->where("status",2)->where($where)->page($start,$num)->order("addtime desc")->select();
        $zl=\app\common\model\Recharge::where("uid",$uid)->where("status",2)->where($where)->sum('money');
        return [$data,$zl];
    }

    public static function recharge_dt($uid,$rid){
       $data=\app\common\model\Recharge::where("id",$rid)->where("uid",$uid)->find();
       if(!$data){
           throw new FailException(['code' => 201,"msg"=>"非法操作"]);
       }
       return $data;
    }
    public static function add_recharge($uid,$money,$pay_password,$shopid=0,$type=1){
        $rechargeid=0;
        Db::startTrans();
        try{
            $money=abs($money);
            //获取该会员资金信息
            $cdata = Db::table("t_capital")->where("type",2)->where("uid",$uid)->where("status",1)->lock(true)->find();
            if(!$cdata){

                throw new FailException(['code' => 201,"msg"=>"资金账户不存在或被冻结","errorCode"=>404]);
            }
            //判断支付密码是否正确
            $user_pay_password=Db::table("t_user")->where("id",$uid)->value("pay_password");

            if(!$user_pay_password){

                throw new FailException(["code"=>201,"msg"=>"支付密码未设置","errorCode"=>432]);
            }
            if($user_pay_password!=$pay_password){

                throw new FailException(['code' => 201,"msg"=>"支付密码错误","errorCode"=>404]);
            }

            $recharge=$cdata['recharge']; //累计充值金额
            $capitalmoney=$cdata['money']; //当前余额
            //判断是否选择了会员等级
            $roleid=Db::table("t_user")->where("id",$uid)->where("status",1)->value("role_id"); //等级id

            if(!$roleid){

                throw new FailException(['code' => 201,"msg"=>"该用户还未选择角色","errorCode"=>404]);
            }
            //获取会员等级信息

            $user_role=Db::table("t_user_role")->where("id",$roleid)->find();

            //判断充值金额是否在该会员的充值范围内
            if($money<$user_role['money']){

                throw new FailException(['code' => 201,"msg"=>"充值金额不得小于最小充值金额","errorCode"=>404]);
            }

            if($money>$user_role['new_recharge']){

                throw new FailException(['code' => 201,"msg"=>"充值金额不得超过最大充值金额","errorCode"=>404]);
            }

            $new_recharge = $recharge + $money;  //最新充值金额

                 //消费型会员无上限

            if ($new_recharge < $user_role['money']) {

                    throw new FailException(["code" => 201, "msg" => "累计充值金额必须满足该会员等级的最小充值金额","errorCode"=>404]);
            }

            if ($new_recharge > $user_role['new_recharge']) {

                    throw new FailException(["code" => 201, "msg" => "累计充值金额不能大于该会员等级的最大充值限额","errorCode"=>404]);
            }

            if($roleid!=3){  //非股东型会员
                Db::table("t_capital")->where("type",2)->where("uid",$uid)->update([
                    "money"=>$capitalmoney+$money,
                    "recharge"=>$new_recharge

                ]);
                $rechargeid=Db::table("t_recharge")->insertGetId([
                    'uid'=>$uid,
                    'cid'=>$cdata['id'],
                    'money'=>$money,
                    'status'=>2,
                    'recharge_num'=>Random::numeric(26),
                    'addtime'=>time()
                ]);

            }else{

                if($money>=100000 && $type==2){ //股东型B

                    $new_fh_bm=Db::table("t_config")->where("name","new_fh_bm")->value("data"); //每股价格

                    if(!$shopid){

                        throw new FailException(['code' => 201,"msg"=>"非法操作，请选择商家","errorCode"=>404]);
                    }

                    $shpdata=Db::table("t_shop")->where("id",$shopid)->where("status",1)->lock(true)->find();

                    if(!$shpdata){

                        throw new FailException(['code' => 201,"msg"=>"非法操作，商家正在维护中","errorCode"=>404]);
                    }

                    if($shpdata['surplus']<abs($new_fh_bm)*10000){

                        throw new FailException(['code' => 201,"msg"=>"商家剩余股份不足","errorCode"=>404]);
                    }
                    $new_surplus=$shpdata['surplus']-abs($new_fh_bm)*10000;
                    Db::table("t_shop")->where("id",$shopid)->where("status",1)->update([
                        'surplus'=>$new_surplus
                    ]);

                    $sy_recharge = $money-abs($new_fh_bm)*10000;

                    Db::table("t_capital")->where("type",2)->where("uid",$uid)->update([
                        "money"=>$capitalmoney+$sy_recharge,
                        "recharge"=>$new_recharge-abs($new_fh_bm)*10000,
                        "putmoney"=>2*($new_recharge-abs($new_fh_bm)*10000),
                        "shareholder_money"=>abs($new_fh_bm)*10000
                    ]);
                  
                      Db::table("t_user")->where("id",$uid)->update([
                        "shop_id"=>$shopid,
                     
                    ]);
                    $rechargeid=Db::table("t_recharge")->insertGetId([
                        'uid'=>$uid,
                        'cid'=>$cdata['id'],
                        'money'=>$sy_recharge,
                        'status'=>2,
                        'recharge_num'=>Random::numeric(26),
                        'addtime'=>time()
                    ]);

                    Db::table("t_capital_water")->insert([
                        "uid"=>$uid,
                        "type"=>4,
                        "cid"=>$cdata['id'],
                        "shopid"=>$shopid,
                        "name"=>"购买商家“".$shpdata['name']."”股份,消耗".(abs($new_fh_bm)*10000)."元",
                        "money"=> 0-abs($new_fh_bm)*10000,
                        "addtime"=>time()
                    ]);


                }else{   //股东型A
                    Db::table("t_capital")->where("type",2)->where("uid",$uid)->update([
                        "money"=>$capitalmoney+$money,
                        "recharge"=>$new_recharge,
                        "putmoney"=>2*$new_recharge
                    ]);
                    $rechargeid=Db::table("t_recharge")->insertGetId([
                        'uid'=>$uid,
                        'cid'=>$cdata['id'],
                        'money'=>$money,
                        'status'=>2,
                        'recharge_num'=>Random::numeric(26),
                        'addtime'=>time()
                    ]);
                }

            }

            Db::table("t_capital_water")->insert([
                "uid"=>$uid,
                "type"=>3,
                "cid"=>$cdata['id'],
                "name"=>"充值 ".$money,
                "money"=> $money,
                "addtime"=>time(),
                "rechange_id"=>$rechargeid
            ]);

           Db::commit();
        }catch (FailException $e){
            Db::rollback();
            throw new FailException(['code' => 201,"msg"=>$e->msg,"errorCode"=>404]);

        }
      

//        $bldata1=Db::table("t_config")->where("name","recharge_fh")->value("data");
//    	$bldata2=Db::table("t_config")->where("name","recharge_cz")->value("data");
//
//        $re1=Recharge::share_out_bonus($uid,$money,$bldata1,$uid,1,$rechargeid);
//        if($re1>1){
//        Recharge::share_out_bonus($re1,$money,$bldata2,$uid,2,$rechargeid);
//
//        }
        
        return ["code"=>200,"msg"=>"充值成功","data"=>$rechargeid];
    }

    //支付宝回调
    public static function alipay_notify($out_trade_no,$trade_no){


        Db::startTrans();
        try{
            $rechargedata= Db::table("t_recharge")->where("recharge_num",$out_trade_no)->find();
            if(!$rechargedata){
                throw new FailException(['code' => 201,"msg"=>"充值失败，请重新充值","errorCode"=>404]);
            }
            if($rechargedata['status']==2){
                throw new FailException(['code' => 201,"msg"=>"已经充值成功，请勿重新支付","errorCode"=>404]);
            }

            $rechargeid=$rechargedata['id'];

            $new_fh_bm=Db::table("t_config")->where("name","new_fh_bm")->value("data"); //每股价格

            $uid=$rechargedata['uid'];

            if(!$rechargedata['shop_id']) {
                $money = $rechargedata['money'];
                $shopid=0;
                $type=1;
            }else{
                $money = $rechargedata['money']+abs($new_fh_bm)*10000;
                $shopid=$rechargedata['shop_id'];
                $type=2;

            }

            $money=abs($money);
            //获取该会员资金信息
            $cdata = Db::table("t_capital")->where("type",2)->where("uid",$uid)->where("status",1)->lock(true)->find();
            if(!$cdata){

                throw new FailException(['code' => 201,"msg"=>"资金账户不存在或被冻结","errorCode"=>404]);
            }


            $recharge=$cdata['recharge']; //累计充值金额
            $capitalmoney=$cdata['money']; //当前余额
            //判断是否选择了会员等级
            $roleid=Db::table("t_user")->where("id",$uid)->where("status",1)->value("role_id"); //等级id

            if(!$roleid){

                throw new FailException(['code' => 201,"msg"=>"该用户还未选择角色","errorCode"=>404]);
            }
            //获取会员等级信息

            $user_role=Db::table("t_user_role")->where("id",$roleid)->find();

            //判断充值金额是否在该会员的充值范围内
            if($money<$user_role['money']){

                throw new FailException(['code' => 201,"msg"=>"充值金额不得小于最小充值金额","errorCode"=>404]);
            }

            if($money>$user_role['new_recharge']){

                throw new FailException(['code' => 201,"msg"=>"充值金额不得超过最大充值金额","errorCode"=>404]);
            }

            $new_recharge = $recharge + $money;  //最新充值金额

            if ($new_recharge < $user_role['money']) {

                throw new FailException(["code" => 201, "msg" => "累计充值金额必须满足该会员等级的最小充值金额","errorCode"=>404]);
            }

            if ($new_recharge > $user_role['new_recharge']) {

                throw new FailException(["code" => 201, "msg" => "累计充值金额不能大于该会员等级的最大充值限额","errorCode"=>404]);
            }

            if($roleid!=3){  //非股东型会员
                Db::table("t_capital")->where("type",2)->where("uid",$uid)->update([
                    "money"=>$capitalmoney+$money,
                    "recharge"=>$new_recharge

                ]);
                Db::table("t_recharge")->where("recharge_num",$out_trade_no)->update([

                    'status'=>2,
                    'alipay_trade_no'=>$trade_no,
                    'addtime'=>time()
                ]);

            }else{

                if($money>=100000 && $type==2){ //股东型B



                    if(!$shopid){

                        throw new FailException(['code' => 201,"msg"=>"非法操作，请选择商家","errorCode"=>404]);
                    }

                    $shpdata=Db::table("t_shop")->where("id",$shopid)->where("status",1)->lock(true)->find();

                    if(!$shpdata){

                        throw new FailException(['code' => 201,"msg"=>"非法操作，商家正在维护中","errorCode"=>404]);
                    }

                    if($shpdata['surplus']<abs($new_fh_bm)*10000){

                        throw new FailException(['code' => 201,"msg"=>"商家剩余股份不足","errorCode"=>404]);
                    }
                    $new_surplus=$shpdata['surplus']-abs($new_fh_bm)*10000;
                    Db::table("t_shop")->where("id",$shopid)->where("status",1)->update([
                        'surplus'=>$new_surplus
                    ]);

                    $sy_recharge = $money-abs($new_fh_bm)*10000;

                    Db::table("t_capital")->where("type",2)->where("uid",$uid)->update([
                        "money"=>$capitalmoney+$sy_recharge,
                        "recharge"=>$new_recharge-abs($new_fh_bm)*10000,
                        "putmoney"=>2*($new_recharge-abs($new_fh_bm)*10000),
                        "shareholder_money"=>abs($new_fh_bm)*10000
                    ]);

                    Db::table("t_user")->where("id",$uid)->update([
                        "shop_id"=>$shopid,

                    ]);
                    Db::table("t_recharge")->where("recharge_num",$out_trade_no)->update([
                        'status'=>2,
                        'alipay_trade_no'=>$trade_no,
                        'addtime'=>time()
                    ]);

                    Db::table("t_capital_water")->insert([   //购买股东流水，非充值流水
                        "uid"=>$uid,
                        "type"=>4,
                        "cid"=>$cdata['id'],
                        "shopid"=>$shopid,
                        "name"=>"购买商家“".$shpdata['name']."”股份,消耗".(abs($new_fh_bm)*10000)."元",
                        "money"=> 0-abs($new_fh_bm)*10000,
                        "addtime"=>time(),

                    ]);


                }else{   //股东型A
                    Db::table("t_capital")->where("type",2)->where("uid",$uid)->update([
                        "money"=>$capitalmoney+$money,
                        "recharge"=>$new_recharge,
                        "putmoney"=>2*$new_recharge
                    ]);
                    Db::table("t_recharge")->where("recharge_num",$out_trade_no)->update([
                        'status'=>2,
                        'alipay_trade_no'=>$trade_no,
                        'addtime'=>time()
                    ]);
                }

            }

            Db::table("t_capital_water")->insert([
                "uid"=>$uid,
                "type"=>3,
                "cid"=>$cdata['id'],
                "name"=>"充值 ".$money,
                "money"=> $money,
                "addtime"=>time(),
                "rechange_id"=>$rechargeid
            ]);

            Db::commit();
        }catch (FailException $e){
            Db::rollback();
            throw new FailException(['code' => 201,"msg"=>$e->msg,"errorCode"=>404]);

        }


//        $bldata1=Db::table("t_config")->where("name","recharge_fh")->value("data");
//        $bldata2=Db::table("t_config")->where("name","recharge_cz")->value("data");
//
//        $re1=Recharge::share_out_bonus($uid,$money,$bldata1,$uid,1,$rechargeid);  //cc
//        if($re1>1){
//            Recharge::share_out_bonus($re1,$money,$bldata2,$uid,2,$rechargeid);
//
//        }

        return ["code"=>200,"msg"=>"充值成功","data"=>$rechargeid];
    }


    //正式充值
    public static function recharge($uid,$money,$pay_password,$shopid=0,$type=1,$recharge_type=0){
        Db::startTrans();
        try{
            $money=abs($money);
            //获取该会员资金信息
            $cdata = Db::table("t_capital")->where("type",2)->where("uid",$uid)->where("status",1)->lock(true)->find();
            if(!$cdata){

                throw new FailException(['code' => 201,"msg"=>"资金账户不存在或被冻结","errorCode"=>404]);
            }
            //判断支付密码是否正确
         //   $user_pay_password=Db::table("t_user")->where("id",$uid)->value("pay_password");

          //  if(!$user_pay_password){

       //         throw new FailException(["code"=>201,"msg"=>"支付密码未设置","errorCode"=>432]);
       //     }
            
       //     if($user_pay_password!=$pay_password){

       //         throw new FailException(['code' => 201,"msg"=>"支付密码错误","errorCode"=>404]);
       //     }

            $recharge=$cdata['recharge']; //累计充值金额

            //判断是否选择了会员等级
            $roleid=Db::table("t_user")->where("id",$uid)->where("status",1)->value("role_id"); //等级id

            if(!$roleid){

                throw new FailException(['code' => 201,"msg"=>"该用户还未选择角色","errorCode"=>404]);
            }
            //获取会员等级信息
          
           

            $user_role=Db::table("t_user_role")->where("id",$roleid)->find();

            //判断充值金额是否在该会员的充值范围内
            if($money<$user_role['money']){

                throw new FailException(['code' => 201,"msg"=>"充值金额不得小于最小充值金额","errorCode"=>404]);
            }

            if($money>$user_role['new_recharge']){

                throw new FailException(['code' => 201,"msg"=>"充值金额不得超过最大充值金额","errorCode"=>404]);
            }

            $new_recharge = $recharge + $money;  //最新充值金额

            //消费型会员无上限

            if ($new_recharge < $user_role['money']) {

                throw new FailException(["code" => 201, "msg" => "累计充值金额必须满足该会员等级的最小充值金额","errorCode"=>404]);
            }

            if ($new_recharge > $user_role['new_recharge']) {

                throw new FailException(["code" => 201, "msg" => "累计充值金额不能大于该会员等级的最大充值限额","errorCode"=>404]);
            }

            if($roleid!=3){  //非股东型会员
                $rechargenum= Random::numeric(26);
                $rechargeid=Db::table("t_recharge")->insertGetId([
                    'uid'=>$uid,
                    'cid'=>$cdata['id'],
                    'money'=>$money,
                    'status'=>1,
                    'recharge_num'=>$rechargenum,
                    'recharge_type'=>$recharge_type,
                    'addtime'=>time()
                ]);

            }else{

                if($money>=100000 && $type==2){ //股东型B

                    $new_fh_bm=Db::table("t_config")->where("name","new_fh_bm")->value("data"); //每股价格

                    $usershopid=Db::table("t_user")->where("id",$uid)->value("shop_id");

                    if($usershopid){
                        throw new FailException(['code' => 201,"msg"=>"您已经参股投资了，不能重复参股","errorCode"=>404]);
                    }

                    if(!$shopid){

                        throw new FailException(['code' => 201,"msg"=>"非法操作，请选择商家","errorCode"=>404]);
                    }

                    $shpdata=Db::table("t_shop")->where("id",$shopid)->where("status",1)->lock(true)->find();

                    if(!$shpdata){

                        throw new FailException(['code' => 201,"msg"=>"非法操作，商家正在维护中","errorCode"=>404]);
                    }

                    if($shpdata['surplus']<abs($new_fh_bm)*10000){

                        throw new FailException(['code' => 201,"msg"=>"商家剩余股份不足","errorCode"=>404]);
                    }


                    $sy_recharge = $money-abs($new_fh_bm)*10000;

                    $rechargenum= Random::numeric(26);
                    $rechargeid=Db::table("t_recharge")->insertGetId([
                        'uid'=>$uid,
                        'cid'=>$cdata['id'],
                        'money'=>$sy_recharge,
                        'status'=>1,
                        'recharge_num'=>$rechargenum,
                        'recharge_type'=>$recharge_type,
                        'addtime'=>time(),
                        'shop_id'=>$shopid
                    ]);




                }else{   //股东型A
                    $rechargenum= Random::numeric(26);
                    $rechargeid=Db::table("t_recharge")->insertGetId([
                        'uid'=>$uid,
                        'cid'=>$cdata['id'],
                        'money'=>$money,
                        'status'=>1,
                        'recharge_num'=>$rechargenum,
                        'recharge_type'=>$recharge_type,
                        'addtime'=>time()
                    ]);
                }

            }


            Db::commit();
        }catch (FailException $e){
            Db::rollback();
            throw new FailException(['code' => 201,"msg"=>$e->msg,"errorCode"=>404]);

        }


        return ["code"=>200,"msg"=>"发起充值","data"=>$rechargeid,"rechargenum"=>$rechargenum];
    }
  
  public static function share_out_bonus($uid,$money,$bldata1,$yuid,$level,$order_id,$shop_fl=0.7){
      Db::startTrans();
      try{

          $pid = Db::table("t_user")->where("id",$uid)->value("pid");
          $money=abs($money);
          $dz=floor($money*(1-$shop_fl)*$bldata1*100/30*100)/100;
          if($pid){
              $username = Db::table("t_user")->where("id",$yuid)->value("username");
              $refereedata = Db::table("t_user")->where("id",$pid)->find();

              $capitalc=Db::table("t_capital")->where("type",2)->where("uid",$pid)->lock(true)->find();  //父级的资金信息

              if($refereedata['status']!=1||$refereedata['role_id']==0){

                  Db::table("t_overflow_log")->insert([
                      "uid"=>$pid,
                      "money"=>$dz,
                      "addtime"=>time()
                  ]);

              }else {

                  if($refereedata['role_id']==1){
                      $ed=Db::table("t_config")->where("name","xf_hbe")->value("data");
                  }elseif($refereedata['role_id']==2){
                      $ed=Db::table("t_config")->where("name","cz_hbe")->value("data");
                  }elseif($refereedata['role_id']==3){
                      $ed=Db::table("t_config")->where("name","gd_hbe")->value("data");
                  }else{
                      $ed=Db::table("t_config")->where("name","xf_hbe")->value("data");
                  }

                  $cc=$capitalc['count_packet_money']+$dz;

              if($cc>$ed && $pid!=1){
                  $packet_money=$capitalc['packet_money']+abs($ed-$capitalc['count_packet_money']); //获得
                  $overmoney= $cc-$ed;
                  Db::table("t_overflow_log")->insert([
                      "uid"=>$pid,
                      "type"=>2,
                      "money"=>$overmoney,
                      "addtime"=>time()
                  ]);

                  Db::table("t_capital")->where("uid",$pid)->where("type",2)->update([
                      "count_packet_money"=>$ed,
                      "packet_money"=>$packet_money
                  ]);
                  Db::table("t_capital_water")->insert([
                      "uid"=>$pid,
                      "type"=>7,
                      "cid"=>$capitalc['id'],
                      "name"=>"用户".$username."消费".($dz)."红包收入".abs($ed-$capitalc['count_packet_money'])."其中溢出".$overmoney,
                      "money"=> abs($ed-$capitalc['count_packet_money']),
                      "addtime"=>time(),
                      "b_username"=>$username,
                      "level"=>$level,
                      "b_money"=>$money,
                      "order_id"=>$order_id
                  ]);

              }else{
                  //  $put_out_money=$capitalc['put_out_money']+$money*$bldata1; //获得

                  $packet_money = $capitalc['packet_money'] + $dz; //获得红包
                  Db::table("t_capital")->where("uid", $pid)->where("type", 2)->update([
                      "count_packet_money" => $capitalc['count_packet_money'] + $dz,
                      "packet_money" => $packet_money
                  ]);
                  Db::table("t_capital_water")->insert([
                      "uid" => $pid,
                      "type" => 7,
                      "cid" => $capitalc['id'],
                      "name" => "用户" . $username . "消费奖励红包" . $dz,
                      "money" => $dz,
                      "addtime" => time(),
                      "b_username" => $username,
                      "level" => $level,
                      "b_money" => $money,
                      "order_id" => $order_id
                  ]);
              }

              }
              Db::commit();

              return $pid;
          }else{
              return 0;
          }

      }catch (Exception $e){
          Db::rollback();
          throw new FailException();

      }

    }
  
}